package com.kumi.crowd.controller;

import com.kumi.crowd.bean.Menu;
import com.kumi.crowd.service.MenuService;
import com.kumi.crowd.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @RequestMapping("/tree")
    @ResponseBody
    public Result<Menu> tree(){

        List<Menu> list = menuService.getAll();

        Menu root = null;

        Map<Integer,Menu> menuMap = new HashMap<>();

        for (Menu menu : list) {
            Integer id = menu.getId();
            menuMap.put(id,menu);

        }

        for (Menu menu : list) {
            Integer pid = menu.getPid();

            if (pid == null){
                root = menu;

                continue;
            }
            Menu father = menuMap.get(pid);
            father.getChildren().add(menu);

        }

        return Result.successData(root);
    }
}
